package com.ruoyi.common.filter;

import com.ruoyi.common.enums.HttpMethod;
import com.ruoyi.common.utils.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 防止XSS攻击的过滤器
 *
 * @author ruoyi
 */
public class XssFilter implements Filter {
    /**
     * 排除链接
     */
    public List<String> excludes = new ArrayList<>();

    /**
     * <简述>初始化操作
     * <详细描述>
     * @author syf
     * @date 2024/8/29 11:38
     * @param filterConfig
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //FilterConfigImpl 实现类中 获取信息： return (String)this.filterInfo.getInitParams().get(name);
        String tempExcludes = filterConfig.getInitParameter("excludes");
        //读取配置文件
        if (StringUtils.isNotEmpty(tempExcludes)) {
            String[] url = tempExcludes.split(StringUtils.SEPARATOR);
            for (int i = 0; url != null && i < url.length; i++) {
                excludes.add(url[i]);
            }
        }
    }

    //过滤
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //在排除路径中直接放行
        if (handleExcludeURL(req, resp)) {
            chain.doFilter(request, response);
            return;
        }
        //不在排除路径，去除html标签，数并重新返回请求
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
        chain.doFilter(xssRequest, response);
    }


    /**
     * <简述>GET DELETE 请求不过滤，其他都过滤是否在排除路径中，true放行
     * <详细描述>
     * @author syf
     * @date 2024/8/29 11:44
     * @param request
     * @param response
     * @return boolean
     */
    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
        String url = request.getServletPath();
        String method = request.getMethod();
        // GET DELETE 不过滤
        if (method == null || HttpMethod.GET.matches(method) || HttpMethod.DELETE.matches(method)) {
            return true;
        }
        return StringUtils.matches(url, excludes);
    }

    //销毁
    @Override
    public void destroy() {

    }
}
